<template>
  <!-- //  3. 通过http-request调用上传的方法 -->
  <el-upload
    class="avatar-uploader"
    action=""
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    :http-request="onUpload"
  >
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script>
// 学习目标：实现使用cos-js-sdk实现文件上传到腾讯云存储桶
// 步骤：
//  1. 下包 cos-js-sdk-v5 导入
import COS from 'cos-js-sdk-v5'
//  2. 实例化COS
const cos = new COS({
  SecretId: 'AKID96pMflgNs77rNglcFl37xZFixykKgnfK',
  SecretKey: 'Vnqpa8SXQDoCMJ6g5IKDtKTWLwKUP6Yn'
})
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
    //   this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
    //   console.log(file)
      const imgList = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp']
      const isJPG = imgList.includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isJPG) {
        this.$message.error('上传头像图片只能图片格式!')
        return false
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
        return false
      }
    },
    onUpload(e) {
      // 4. 调用cos.putObject实现上传
    //   console.log(e)
      cos.putObject({
        Bucket: 'hm-rlzyxt-1312618038', /* 必须 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: e.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: e.file
      }, (err, data) => {
        // 5. 子传父input事件
        if (!err) {
        //   console.log(data)
          this.$emit('input', 'https://' + data.Location)
        }
      })
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
